const BaseController = require('../core/BaseController');

module.exports = class extends BaseController {
  constructor(props) {
    super(props);
    this.tableName = 'product';
  }

  async get() {
    const { ctx, app } = this;
    const rs = await app.mysql.get(this.tableName, { id: ctx.query.id });
    if (rs.img_id) {
      rs.img = await app.mysql.get('img', { id: rs.img_id });
      rs.img = rs.img.path;
    }
    if (rs.brand_id) {
      rs.brand = await app.mysql.get('brand', { id: rs.brand_id });
      rs.brand = rs.brand.name;
    }
    if (rs.cate_id) {
      rs.cate = await app.mysql.get('cate', { id: rs.cate_id });
      rs.cate = rs.cate.name;
    }
    // 获取图片
    return rs && rs.id > 0 ? ctx.success(ctx.helper.toPlainObject(rs)) : ctx.fail('找不到这个ID相关的数据');
  }

  async page() {
    const { ctx, app } = this;
    let { currentPage = 1, pageSize = 2, key = '' } = ctx.query;
    currentPage = parseInt(currentPage);
    pageSize = parseInt(pageSize);
    // 获取图片
    const all = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and name like "%${key}%"`);
    const list = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and name like "%${key}%" order by create_time desc limit ${(currentPage - 1) * pageSize}, ${pageSize}`);
    for (let i = 0; i < list.length; i++) {
      if (list[i].img_id) {
        list[i].img = await app.mysql.get('img', { id: list[i].img_id });
        list[i].img = list[i].img.path;
      }
      if (list[i].brand_id) {
        list[i].brand = await app.mysql.get('brand', { id: list[i].brand_id });
        list[i].brand = list[i].brand.name;
      }
      if (list[i].cate_id) {
        list[i].cate = await app.mysql.get('cate', { id: list[i].cate_id });
        list[i].cate = list[i].cate.name;
      }
    }
    const count = all.length;
    const total = Math.ceil(count / pageSize);
    return list ? ctx.success({ currentPage, total, count, list }) : ctx.fail('查询分页失败');
  }

}

